function findMeta(code) {
	var meta = frameworkMetaManager.findView(code);
	return meta;
}


Ext.onReady(function(){

    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    var myData = [
        ['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
        ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
        ['Altria Group Inc',83.81,0.28,0.34,'9/1 12:00am'],
        ['American Express Company',52.55,0.01,0.02,'9/1 12:00am'],
        ['American International Group, Inc.',64.13,0.31,0.49,'9/1 12:00am'],
        ['AT&T Inc.',31.61,-0.48,-1.54,'9/1 12:00am'],
        ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'],
        ['Caterpillar Inc.',67.27,0.92,1.39,'9/1 12:00am'],
        ['Citigroup, Inc.',49.37,0.02,0.04,'9/1 12:00am'],
        ['E.I. du Pont de Nemours and Company',40.48,0.51,1.28,'9/1 12:00am'],
        ['Exxon Mobil Corp',68.1,-0.43,-0.64,'9/1 12:00am'],
        ['General Electric Company',34.14,-0.08,-0.23,'9/1 12:00am'],
        ['General Motors Corporation',30.27,1.09,3.74,'9/1 12:00am'],
        ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'],
        ['Honeywell Intl Inc',38.77,0.05,0.13,'9/1 12:00am'],
        ['Intel Corporation',19.88,0.31,1.58,'9/1 12:00am'],
        ['International Business Machines',81.41,0.44,0.54,'9/1 12:00am'],
        ['Johnson & Johnson',64.72,0.06,0.09,'9/1 12:00am'],
        ['JP Morgan & Chase & Co',45.73,0.07,0.15,'9/1 12:00am'],
        ['McDonald\'s Corporation',36.76,0.86,2.40,'9/1 12:00am'],
        ['Merck & Co., Inc.',40.96,0.41,1.01,'9/1 12:00am'],
        ['Microsoft Corporation',25.84,0.14,0.54,'9/1 12:00am'],
        ['Pfizer Inc',27.96,0.4,1.45,'9/1 12:00am'],
        ['The Coca-Cola Company',45.07,0.26,0.58,'9/1 12:00am'],
        ['The Home Depot, Inc.',34.64,0.35,1.02,'9/1 12:00am'],
        ['The Procter & Gamble Company',61.91,0.01,0.02,'9/1 12:00am'],
        ['United Technologies Corporation',63.26,0.55,0.88,'9/1 12:00am'],
        ['Verizon Communications',35.57,0.39,1.11,'9/1 12:00am'],
        ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am']
    ];

    function change(val){
        if(val > 0){
            return '<span style="color:green;">' + val + '</span>';
        }else if(val < 0){
            return '<span style="color:red;">' + val + '</span>';
        }
        return val;
    }

    function pctChange(val){
        if(val > 0){
            return '<span style="color:green;">' + val + '%</span>';
        }else if(val < 0){
            return '<span style="color:red;">' + val + '%</span>';
        }
        return val;
    }

    // create the data store
    var store = new Ext.data.SimpleStore({
        fields: [
           {name: 'company'},
           {name: 'price', type: 'float'},
           {name: 'change', type: 'float'},
           {name: 'pctChange', type: 'float'},
           {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
        ]
    });
    store.loadData(myData);

    // create the Grid
    var grid = new Ext.grid.GridPanel({
        store: store,
        columns: [
            {id:'company',header: "Company", width: 160, sortable: true, dataIndex: 'company'},
            {header: "Price", width: 75, sortable: true, renderer: 'usMoney', dataIndex: 'price'},
            {header: "Change", width: 75, sortable: true, renderer: change, dataIndex: 'change'},
            {header: "% Change", width: 75, sortable: true, renderer: pctChange, dataIndex: 'pctChange'},
            {header: "Last Updated", width: 85, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'}
        ],
        stripeRows: true,
        autoExpandColumn: 'company',
        height:350,
        width:600,
        title:'Array Grid'
    });

    grid.render('grid-example');

    grid.getSelectionModel().selectFirstRow();
});

// -----------------------------------------------------------------------------------------------------------------------------------------
// templates for form and fields
var DEFAULT_TEMPLATE = {
	form:{
		title: 'Template Form Title, Change this please!',
		labelAlign:'left',
		buttonAlign:'right',
		frame:true,
		labelWidth:80,
		width:600
	},
	form_row:{
		layout:'column',
		border:false,
		labelSeparator:'：'
	},
	form_cell:{
		layout: 'form',
		border:false
	},
	textfield:{
		xtype:'textfield',
		fieldLabel: "{textfield}",
		name: "{textfield}",
		anchor:'90%'
	},
	textarea:{
		xtype:'textarea',
		fieldLabel:'',
		anchor:'90%'
	},
	numberfield:{
		xtype:'numberfield',
		fieldLabel: "{numberfield}",
		name: "{numberfield}"
	},
	timefield:{
		xtype:'timefield',
		fieldLabel: '{timefield}',
		name: 'time'
	},
	datefield:{
		xtype:'datefield',
		fieldLabel: '{datefield}',
		name: '{datefield}',
		anchor:'90%'
	},
	radio:{
		columnWidth:.25,
		layout: 'form',
		border:false
	},
	radiooption:{
		xtype:'radio',
		fieldLabel: '{radio}',
		boxLabel:'{radio}',
		name: '{radio}',
		checked:true,
		inputValue:'{radio}',
		anchor:'95%'
	},
	checkbox:{
		columnWidth:.35,
		layout: 'form',
		border:false
	},
	checkboxoption:{
		xtype:'checkbox',
		fieldLabel: '{checkbox}',
		boxLabel:'{checkbox}',
		name: '{checkbox}',
		inputValue:'{checkbox}',
		anchor:'95%'
	},
	combo:{
		xtype:'combo',
		valueField :"primaryKey",
		displayField: "displayName",
		mode:'local',
		forceSelection: true,
		blankText:'Selections',
		emptyText:'Selections',
		hiddenName:'{combo}',
		editable: false,
		triggerAction: 'all',
		allowBlank:false,
		fieldLabel: '{combo}',
		name: '{combo}',
		anchor:'90%'
	},
	tabpanel:{
		xtype:'tabpanel',
		plain:true,
		activeTab:0,
		height:235,
		autoScroll: true,
		bodyStyle:'padding:10px',
		defaults:{}
	},
	tabpage:{
		layout:'form',
		//defaultType:'textfield',
		anchor:'90%'
	}
};
// form item builders;
function cloneObject(input) {
	if(typeof(input) == "object") {
		var result = {};
		for(x in input) {
			var tmp = input[x];
			if(typeof(tmp) == "object") {
				result[x] = cloneObject(tmp);
			} else {
				result[x] = input[x];
			}
		}
		return result;
	} else {
		return input;
	}
}

function copyProperties(from, to, forceAll) {
	for(key in from) {
		var fromValue = from[key];
		if(forceAll) {
			to[x] = fromValue;
			continue;
		} else {
			if(!fromValue) continue;

			var toValue = to[key];
			if(toValue) {
				if(typeof(fromValue) != typeof(toValue))
					to[key] = fromValue;
			} else {
				to[key] = fromValue;
			}
		}	// end else
	}
}

function printObject(input) {
	if(input instanceof Array) {
	}
}

function __typeof__(objClass) { 
    if ( objClass != undefined && objClass.constructor ) { 
        var strFun = objClass.constructor.toString(); 
        var className = strFun.substr(0, strFun.indexOf('(')); 
        className = className.replace('function', ''); 
        return className.replace(/(^\s*)|(\s*$)/ig, ''); 
    } 
    return typeof(objClass); 
}
function setCookie(name,value) {
	var Days = 30; //expired after 30 days
	var exp  = new Date();    //new Date("December 31, 9998");
	exp.setTime(exp.getTime() + Days*24*60*60*1000);
	document.cookie = name + "="+ escape(value) +";expires="+ exp.toGMTString();
}
function getCookie(name) {
	var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
	if(arr != null) 
		return unescape(arr[2]); 
	return null;
}
function delCookie(name) {
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval=getCookie(name);
	if(cval!=null) document.cookie=name +"="+cval+";expires="+exp.toGMTString();
}
/**
 * build formitems from meta property
 * @metaProperty property come from meta database
 * @value the default value of component
 * @properties customezation properties of component,addition of template definitions
 * @template the default definition of component
 * @container the parent component of the result
 * @return the built result
 */
function buildFormItemFromMetaProperty(metaProperty, value, template, container) {
	if(!template) template = DEFAULT_TEMPLATE;
	var dataType = metaProperty.dataType.toLowerCase();
	var displayType = metaProperty.displayType;
	var result = null;
	if(dataType == "string") {
		if(displayType == "combo" || displayType == "radio" || displayType == "checkbox") {
			if(displayType == "combo") {
				result =  buildCombo(metaProperty, value, template, container);
			} else if(displayType == "radio") {
				result =  buildRadioGroup(metaProperty, value, template, container);
			} else {
				result =  buildCheckboxGroup(metaProperty, value, template, container);
			}
		} else if(displayType == "textarea"){
			result =  buildTextArea(metaProperty, value, template, container);
		} else{
			result =  buildTextField(metaProperty, value, template, container);
		}
	} else if(dataType == "int" || dataType == "integer" || dataType == "float" || dataType == "double") {
		result =  buildNumberField(metaProperty, value, template, container);
	} else if(dataType == "date") {
		result =  buildDateField(metaProperty, value, template);
	} else if(dataType == "time") {
		result =  buildTimeField(metaProperty, value, template, container);
	} else {	// if other non-simple datatype
		if(displayType == "combo") {
			result =  buildCombo(metaProperty, value, template, container);
		} else if(displayType == "radio") {
			result =  buildRadioGroup(metaProperty, value, template, container);
		} else {
			result =  buildCheckboxGroup(metaProperty, value, template, container);
		}
	}
	// add all common properties to component;
	if(result instanceof Array) {
	} else {
		result.name = metaProperty.name;
		result.id = metaProperty.name;
		result.fieldLabel = metaProperty.displayTitle;
		result.allowBlank = !metaProperty.required;
		if(dataType != "time")
			if(value) result.value = value;
	}
	//
	return result;
}

function buildTextField(metaProperty, value, template, container) {
	if(!template) template = DEFAULT_TEMPLATE;
	var result = cloneObject(template.textfield);
	//
	var displayType = metaProperty.displayType;
	if(displayType) {
		if(displayType == "password") {
			result.inputType = "password";
		} else if(displayType == "email" || displayType == "url" || displayType == "alpha" || displayType == "alphanum"){
			result.vtype = displayType;
		}
	}
	return result;
}

function buildTextArea(metaProperty, value, template, container) {
	if(!template) template = DEFAULT_TEMPLATE;
	var result = cloneObject(template.textarea);
	return result;
}

function buildNumberField(metaProperty, value, template, container) {
	if(!template) template = DEFAULT_TEMPLATE;
	var result = cloneObject(template.numberfield);
	return result;
}

function buildDateField(metaProperty, value, template, container) {
	if(!template) template = DEFAULT_TEMPLATE;
	var result = cloneObject(template.datefield);
	return result;
}

function buildTimeField(metaProperty, value, template, container) {
	if(!template) template = DEFAULT_TEMPLATE;
	var result = cloneObject(template.timefield);
	return result;
}

function buildCombo(metaProperty, value, template, container) {
	if(!template) template = DEFAULT_TEMPLATE;
	var result = cloneObject(template.combo);
	//
	if(metaProperty.dataStore) {
		result.valueField = metaProperty.dataStore.fields[0];
		result.displayField = metaProperty.dataStore.fields[1];
		result.store = new Ext.data.SimpleStore(metaProperty.dataStore);
		result.mode = "local";
		result.blankText = metaProperty.displayTitle;
		result.emptyText = metaProperty.displayTitle;
		result.hiddenName = metaProperty.name;
	} else {
	}
	return result;
}

function buildRadioGroup(metaProperty, value, template, container) {
	if(!template) template = DEFAULT_TEMPLATE;
	//
	var cellWidth = container.cell.columnWidth;
	var dataStore = metaProperty.dataStore;
	var optionLength = dataStore.data.length;
	var optionWidth = cellWidth / (optionLength + 1);
	var firstWidth = optionWidth;
	if(optionLength > 1) firstWidth = optionWidth * 2;
	//
	var cells = [];
	for(var i=0; i< optionLength; i++){
		var primaryKey = dataStore.data[i][0];
		var displayTitle = dataStore.data[i][1];
		//
		var cell = cloneObject(template.radio);
		var item = cloneObject(template.radiooption);
		if(i == 0) {
			cell.columnWidth = firstWidth;
			item.fieldLabel = metaProperty.displayTitle;
		} else {
			cell.columnWidth = optionWidth;
			item.fieldLabel = "";
			cell.labelWidth = 0;
			item.labelSeparator = "";
		}
		item.name = metaProperty.name;
		item.boxLabel = displayTitle;
		item.inputValue = primaryKey;
		item.checked = (value == primaryKey);
		cell.items = [item];
		cells.push(cell);
	}
	return cells;
}

function buildCheckboxGroup(metaProperty, value, template, container) {
	if(!template) template = DEFAULT_TEMPLATE;
	//
	var cellWidth = container.cell.columnWidth;
	var dataStore = metaProperty.dataStore;
	var optionLength = dataStore.data.length;
	var optionWidth = cellWidth / (optionLength + 1);
	var firstWidth = optionWidth;
	if(optionLength > 1) firstWidth = optionWidth * 2;
	//
	var cells = [];
	for(var i=0; i< optionLength; i++){
		var primaryKey = dataStore.data[i][0];
		var displayTitle = dataStore.data[i][1];
		//
		var cell = cloneObject(template.checkbox);
		var item = cloneObject(template.checkboxoption);
		if(i == 0) {
			cell.columnWidth = firstWidth;
			item.fieldLabel = metaProperty.displayTitle;
		} else {
			cell.columnWidth = optionWidth;
			item.fieldLabel = "";
			cell.labelWidth = 0;
			item.labelSeparator = "";
		}
		item.boxLabel = displayTitle;
		item.inputValue = primaryKey;
		item.name = metaProperty.name;
		item.checked = false;
		if(value instanceof Array) {
			for(var j=0; j<value.length; j++){
				if(primaryKey == value[j]) {
					item.checked = true;
					break;
				}
			}
		} else {
			item.checked = (primaryKey == value);
		}
		cell.items = [item];
		cells.push(cell);
	}
	return cells;
}

/**
 * renderObject the form render renderObject, default is document.body
 * properties descript the form
 * button descriptors
 * meta metaView object from meta database
 */
function FormBuilder(renderObject, formAttributes, metaView, container, template) {
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	//
	if(!renderObject) renderObject = document.body;
	if(!template) template = DEFAULT_TEMPLATE;
	// private properties
	this.columnWidth = 1;
	this.title = "";
	this.remarks = "";
	this.editable = false;
	this.queryString = "";
	this.boClassName = "";

	// private functions
	this.initProperties = function() {
		if(metaView.displayColumnCount > 1) {
			this.columnWidth = 1.0 / metaView.displayColumnCount;
		}
		if(metaView.name)		this.title = metaView.name;
		if(metaView.remarks)	this.remarks = metaView.remarks;
		if(metaView.queryString)	this.queryString = metaView.queryString;
		if(metaView.queryString)	this.queryString = metaView.queryString;
		this.editable = metaView.editable;
	}

	this.buildItems = function(formMetaView) {
		var items = new Array();
		var properties = formMetaView.properties;
		var displayColumnCount = formMetaView.displayColumnCount;
		if(displayColumnCount == 0) displayColumnCount = 1;
		var columnWidth = 1.0 / displayColumnCount;
		var bindObject = formMetaView.bindObject;
		if(properties) {
			var pointer = 0;
			while(pointer < properties.length) {
				var row = cloneObject(template.form_row);
				//
				var rowItems = [];
				var cellCount = 0;
				for(var i = 0; i < displayColumnCount; i++){
					var prop = properties[i + pointer];
					if(!prop) break;
					if(prop.colspan > 1) i += prop.colspan - 1;
					//
					var cellWidth = columnWidth * prop.colspan;
					if(cellWidth > 1.0) cellWidth = 1.0;
					var cell = cloneObject(template.form_cell);
					copyProperties({columnWidth:cellWidth, layout:"form"}, cell);
					var container = {row:row, cell:cell};
					var value = "";
					if(bindObject) value = bindObject[prop.name];
					var buildResult = buildFormItemFromMetaProperty(prop, value, template, container);
					if(buildResult instanceof Array){
						for(var j=0; j<buildResult.length; j++){
							rowItems.push(buildResult[j]);
						}
					} else {
						cell.items = [buildResult];
						rowItems.push(cell);
					}
					cellCount ++;
				}
				row.items = rowItems;
				items.push(row);
				//
				pointer += cellCount;
				if(pointer >= properties.length) break;
			}
		}
		return items;
	}

	this.buildButtons = function(formMetaView) {
		return formMetaView.buttons;
	}
	// build form
	this.buildForm = function() {
		var mainForm		= cloneObject(template.form);
		mainForm.title		= metaView.name;
		copyProperties(formAttributes, mainForm, true);
		mainForm.items		= this.buildItems(metaView);
		mainForm.buttons	= this.buildButtons(metaView);
		//
		if(metaView.children) {
			var tabPanel = cloneObject(template.tabpanel);
			var tabPanelItems = [];
			for(var i=0; i< metaView.children.length; i++) {
				var childView = metaView.children[i];
				var tabPage = cloneObject(template.tabpage);
				tabPage.title = childView.name;
				tabPage.items = this.buildItems(childView);
				tabPage.buttons = this.buildButtons(childView);
				tabPanelItems.push(tabPage);
			}
			tabPanel.items = tabPanelItems;
			mainForm.items.push(tabPanel);
		}
		var tab = {
			xtype:'tabpanel',
			plain:true,
			activeTab: 0,
			height:235,
			defaults:{bodyStyle:'padding:10px'},
			items:[{
				title:'登录信息',
				layout:'form',
				defaults: {width: 230},
				defaultType: 'textfield',
	 
				items: [{
					fieldLabel: '登录名',
					name: 'loginID',
					allowBlank:false,
					vtype:'alphanum',
					allowBlank:false
				},{
					inputType:'password',
					fieldLabel: '密码',
					name: 'password',
					allowBlank:false
				}]
			},{
				title:'数字时间字母',
				layout:'form',
				defaults: {width: 230},
				defaultType: 'textfield',
	 
				items: [{
						   xtype:'numberfield',
					fieldLabel: '数字',
					name: 'number'
				},{
						   xtype:'timefield',
					fieldLabel: '时间',
					name: 'time'
				},{
					fieldLabel: '纯字母',
					name: 'char',
					vtype:'alpha'
				}]
			},{
				title:'文本区域',
				layout:'fit',
				items: {
					xtype:'textarea',
					id:'area',
					fieldLabel:''
				}
			}]
		};
		mainForm.items.push(tab);
		//
		return mainForm;
	}

	this.render = function() {
		this.form = new Ext.FormPanel(this.buildForm());
		this.form.render(renderObject);
	}
	//
	this.form = null;
	this.initProperties();
	this.render();
}